import { ipcMain } from 'electron';
import { gitService } from '../services/GitService';

export function setupGitHandlers(): void {
  // 初始化Git仓库
  ipcMain.handle('git:initRepository', async (_, filePath: string) => {
    try {
      return await gitService.initRepository(filePath);
    } catch (error) {
      console.error('Failed to initialize Git repository:', error);
      throw new Error(`无法初始化Git仓库: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  });

  // 检查文件是否在Git仓库中
  ipcMain.handle('git:isFileInRepository', async (_, filePath: string) => {
    try {
      return await gitService.isFileInRepository(filePath);
    } catch (error) {
      console.error('Failed to check if file is in repository:', error);
      return false;
    }
  });

  // 添加文件到Git仓库
  ipcMain.handle('git:addFile', async (_, filePath: string, message?: string) => {
    try {
      return await gitService.addFile(filePath, message);
    } catch (error) {
      console.error('Failed to add file to repository:', error);
      throw new Error(`无法添加文件到Git仓库: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  });

  // 获取文件的Git历史记录
  ipcMain.handle('git:getFileHistory', async (_, filePath: string) => {
    try {
      return await gitService.getFileHistory(filePath);
    } catch (error) {
      console.error('Failed to get file history:', error);
      throw new Error(`无法获取文件历史记录: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  });

  // 获取文件在特定提交的内容
  ipcMain.handle('git:getFileContentAtCommit', async (_, filePath: string, commitHash: string) => {
    try {
      return await gitService.getFileContentAtCommit(filePath, commitHash);
    } catch (error) {
      console.error('Failed to get file content at commit:', error);
      throw new Error(`无法获取文件在特定提交的内容: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  });

  // 获取文件在两个提交之间的差异
  ipcMain.handle('git:getFileDiff', async (_, filePath: string, commitHash1: string, commitHash2: string) => {
    try {
      return await gitService.getFileDiff(filePath, commitHash1, commitHash2);
    } catch (error) {
      console.error('Failed to get file diff:', error);
      throw new Error(`无法获取文件差异: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  });

  // 检查是否有未提交的更改
  ipcMain.handle('git:hasUncommittedChanges', async (_, filePath: string) => {
    try {
      return await gitService.hasUncommittedChanges();
    } catch (error) {
      console.error('Failed to check for uncommitted changes:', error);
      return false;
    }
  });

  // 提交当前更改
  ipcMain.handle('git:commitChanges', async (_, filePath: string, message: string) => {
    try {
      return await gitService.commitChanges(message);
    } catch (error) {
      console.error('Failed to commit changes:', error);
      throw new Error(`无法提交更改: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  });
}